package juc.reentrantlock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁：
 * 读锁共享，读写、写写互斥
 */
public class ReadWriteLockTest {

    static class DataContainer {

        // 要保护的共享数据
        private Object data;

        private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        // 读锁
        private final ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
        // 写锁
        private final ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

        /**
         * 读操作
         * @return Object
         */
        public Object read() {
            System.out.println("获取读锁...");
            readLock.lock();
            try {
                System.out.println("读取操作");
                Thread.sleep(1000);
                return data;
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            } finally {
                System.out.println("释放读锁...");
                readLock.unlock();
            }
        }

        /**
         * 写操作
         */
        public void write() {
            System.out.println("获取写锁...");
            writeLock.lock();
            try {
                System.out.println("写入操作");
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("释放写锁...");
                writeLock.unlock();
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        DataContainer dataContainer = new DataContainer();

        Thread t1 = new Thread(()->{
             dataContainer.read();
//            dataContainer.write();
        },"t1");

        Thread t2 = new Thread(()->{
//             dataContainer.read();
            dataContainer.write();
        },"t2");

        t1.start();
        Thread.sleep(100);
        t2.start();
    }

}
